<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="width" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './category.data';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { list, saveOrUpdateCategory } from './category.api';
import { useAdapt } from '/@/hooks/system/useAutoAdapt.ts';
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const { width } = useAdapt({ xl: 650, lg: 650, md: 650, sm: 650, xs: 650});
const attrs = useAttrs()
const isUpdate = ref(true);
const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
  labelCol: {
    md: { span: 4 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 18 },
  },
  schemas: formSchema,
  showActionButtonGroup: false
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields()
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  console.log("use data: ", data);
  // 转成select结构
  const keywords = data?.record?.keywords?.split(',').map(e => {
    return {label: e, value: e}
  })

  //获取下拉树信息
  const treeData = await list({});
  updateSchema([
    {
      field: 'parentId',
      componentProps: { treeData },
    }
  ]);

  // 无论新增还是编辑，都可以设置表单值
  if (typeof data.record === 'object') {
    let values = { 
      ...data.record, 
      keywords,
      parentId: data.record.parentId === '0' ? null : data.record.parentId
    }
    setFieldsValue(values)
  }
});
//获取弹窗标题
const getTitle = computed(() => (!unref(isUpdate) ? '新增分类' : '编辑分类'));
//提交事件
async function handleSubmit() {
  try {
    const values = await validate()
    console.log("submit data: ", values);

    if (isUpdate.value && values.parentId === values.id) {
      createMessage.error('上级分类不能选择自己')
      return
    }

    if (values.keywords?.includes('[object Object]')) {
      values.keywords = null
    }

    setDrawerProps({ confirmLoading: true });
    await saveOrUpdateCategory({ ...values }, unref(isUpdate));
    closeDrawer();
    createMessage.success(`${getTitle.value}成功`)
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>

